/****************************************************************************
    Kantaoke, karaoke game made with BennuGD.
    Copyright (C) 2010 Joseba García Echebarria

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/

#ifndef __CHARSET_INC__
#define __CHARSET_INC__

/* Filename is the name of the filke which defines the charset */
Function readchars(string pointer chars, string filename, int limit)
Private
  int fd=0,i=0;
  string line="";
  
Begin
  fd = fopen(filename, O_READ);
  if(fd == 0)
    return -1;
  end;
  for(i=0; i<=limit; i++)
    if(!feof(fd))
      chars[i] = fgets(fd);
    else
      break;
    end;
  end;
  fclose(fd);
End;

/* Try to determine the charset of filename by looking known characters from that charset */
/* in order to know them, it will look for all the files in the {datadir}/charset_finder folder */
Function string determine_charset(string filename)
Private
  int fd = 0, i=0, limit=10;
  string line = "", charset = "";
  string chars[10];
End
  
Begin
  fd = fopen(filename, O_READ);
  if(fd == 0)
    return -1;
  end;

  /* Read all available charsets */
  while( (charset = glob(datadir+"charset_finder/*")) != "")
    if(charset != "." && charset != ".." && fileinfo.directory == false)
      readchars(&chars, datadir+"charset_finder/"+charset, limit);
      //Read the entire file looking for UTF-8 characters
      while(!feof(fd))
        line = fgets(fd);
        for(i=0; i <= limit; i++)
          if(find(line, chars[i]) != -1)
            fclose(fd);
            return charset;
          end;
        end;
      end;
      // Position the reading cursor at the begining of the file
      fseek(fd, 0, SEEK_SET);
    end;
  end;

  fclose(fd);
  dbg_print("Cannot determine charset of file "+filename+"; assuming it's"+
  					" ISO-8859-1, but that's probably wrong.");
  return "ISO-8859-1";    // Default value, probably wrong
End;

#endif
